package com.example.competionmanagebackend.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.competionmanagebackend.entity.Teams;
import com.example.competionmanagebackend.entity.Users;
import com.example.competionmanagebackend.service.TeamsService;
import com.example.competionmanagebackend.service.UsersService;
import com.example.competionmanagebackend.utils.PageRequest;
import com.example.competionmanagebackend.utils.PageResult;
import com.example.competionmanagebackend.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/teams")
public class TeamsController {

    @Autowired
    private TeamsService teamsService;

    @Autowired
    private UsersService usersService;

    @GetMapping("/users")
    public ResponseEntity<Result<List<Users>>> getAllUsers() {
        // 从数据库获取所有用户
        List<Users> allUsers = usersService.getAllUsers();
        // 过滤只留下 role 为 2 的用户
        List<Users> filteredUsers = allUsers.stream()
                .filter(user -> user.getRole() != null && user.getRole() == 2)
                .collect(Collectors.toList());
        return Result.success(filteredUsers);
    }


    @PostMapping("/getTeamsPage")
    public ResponseEntity<Result<PageResult<Teams>>> getTeamsPage(@RequestBody PageRequest pageRequest,
                                                                  HttpServletRequest request) {
        // 从请求中获取全局 Token 拦截器设置的用户名属性
        String username = (String) request.getAttribute("username");
        if (username == null) {
            return Result.fail(401, "Invalid or missing token");
        }
        Users user = usersService.getUserByUsername(username);

        Page<Teams> page = new Page<>(pageRequest.getCurrentPage(), pageRequest.getPageSize());
        if (user.getRole() != null && user.getRole() == 2) {
            // role == 2 时，只查询该用户相关的队伍
            List<Teams> teams = teamsService.getTeamsByUserId(user.getId());
            int total = teams.size();
            int fromIndex = (int) ((pageRequest.getCurrentPage() - 1) * pageRequest.getPageSize());
            int toIndex = (int) Math.min(fromIndex + pageRequest.getPageSize(), total);
            List<Teams> pagedTeams = fromIndex < total ? teams.subList(fromIndex, toIndex) : List.of();
            page.setRecords(pagedTeams);
            page.setTotal(total);
        } else {
            // 其他角色查询所有队伍
            page = teamsService.getTeamsPage(pageRequest.getCurrentPage(), pageRequest.getPageSize());
        }

        List<Users> allUsers = usersService.getAllUsers();
        List<Teams> enrichedTeams = page.getRecords().stream().map(team -> {
            Users captain = allUsers.stream()
                    .filter(u -> u.getId().equals(team.getUserId()))
                    .findFirst()
                    .orElse(null);
            if (captain != null) {
                team.setUserName(captain.getUserName());
            }
            if (team.getMemberIds() != null && !team.getMemberIds().isEmpty()) {
                String memberNames = allUsers.stream()
                        .filter(u -> team.getMemberIds().contains(String.valueOf(u.getId())))
                        .map(Users::getUserName)
                        .collect(Collectors.joining(", "));
                team.setMemberNames(memberNames);
            }
            return team;
        }).collect(Collectors.toList());

        Page<Teams> enrichedPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        enrichedPage.setRecords(enrichedTeams);
        PageResult<Teams> result = new PageResult<>(enrichedPage);
        return Result.success(result);
    }

    @PostMapping("/edit")
    public ResponseEntity<Result<Teams>> editTeam(@RequestBody Teams team, HttpServletRequest request) {
        String username = (String) request.getAttribute("username");
        if (username == null) {
            return Result.fail(401, "Invalid or missing token");
        }
        if (team.getId() == null) {
            teamsService.insertTeam(team);
        } else {
            teamsService.updateTeam(team);
        }
        return Result.success(team);
    }

    @GetMapping("/delete")
    public ResponseEntity<Result<String>> deleteTeam(@RequestParam("id") Integer id,
                                                     HttpServletRequest request) {
        String username = (String) request.getAttribute("username");
        if (username == null) {
            return Result.fail(401, "Invalid or missing token");
        }
        try {
            teamsService.deleteTeam(id);
            return Result.success("删除成功");
        } catch (org.springframework.dao.DataIntegrityViolationException e) {
            // 捕获外键约束相关的异常，返回自定义错误提示
            return Result.fail(400, "该队伍已报名赛事，请先删除报名记录");
        }
    }

}
